package org.jeemp.neety.io.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author JackRen
 * @date 2021-11-12 16:13
 * @description:同步阻塞IO模型
 */
public class BIOServer {
    //服务端网络IO模型的封装对象
    ServerSocket serverSocket;
    public  BIOServer(int port) {
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("BIO服务已启动，监听端口是：" + port);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *
     * @author JackRen
     * @date 2021/11/12
     * @return 开始监听，并处理逻辑
     **/
    public void listen() throws IOException {
        //循环监听
        while (true) {
            //等待客户端连接，阻塞方法
            //Socket数据发送者在服务端的引用
            Socket client = serverSocket.accept();
            System.out.println(client.getPort());

            //读取传送数据
            InputStream is =client.getInputStream();
            //客户端数据发送到网卡，机器得到数据读取到JVM内存中
            byte [] buff = new byte[1024];
            int len = is.read(buff);
            if (len > 0) {
                String msg  = new String(buff,0,len);
                System.out.println("收到数据："+msg);
            }

        }
    }


    public static void main(String[] args) throws IOException {
       BIOServer bioServer =  new BIOServer(8080);
       bioServer.listen();
    }

}
